<template>
  <div class="page-container">
    <div class="page-header">
      <h2>运动类型管理</h2>
      <p>管理系统支持的运动类型</p>
    </div>
    
    <el-card class="action-card">
      <div class="action-container">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加运动类型
        </el-button>
      </div>
    </el-card>
    
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="exerciseTypes"
        style="width: 100%"
        border
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
        />
        <el-table-column
          prop="name"
          label="名称"
          min-width="120"
        />
        <el-table-column
          prop="category"
          label="分类"
          min-width="120"
        >
          <template #default="scope">
            {{ getCategoryDisplayName(scope.row.category) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="caloriesPerMinute"
          label="卡路里/分钟"
          min-width="120"
        >
          <template #default="scope">
            {{ scope.row.caloriesPerMinute }} kcal
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          width="150"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              circle
              @click="handleEdit(scope.row)"
            >
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button
              type="danger"
              size="small"
              circle
              @click="handleDelete(scope.row)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑运动类型' : '添加运动类型'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="输入运动类型名称" />
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="选择分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="卡路里/分钟" prop="caloriesPerMinute">
          <el-input-number
            v-model="form.caloriesPerMinute"
            :min="0.1"
            :max="50"
            :step="0.1"
            :precision="1"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="输入描述信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllExerciseTypes,
  createExerciseType,
  updateExerciseType,
  deleteExerciseType
} from '@/api/exerciseType'

const loading = ref(false)
const exerciseTypes = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref(null)

// 当前编辑的ID
const currentId = ref(null)

// 表单数据
const form = ref({
  name: '',
  category: '',
  caloriesPerMinute: 5.0,
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入运动类型名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  caloriesPerMinute: [
    { required: true, message: '请输入每分钟消耗卡路里数', trigger: 'blur' },
    { type: 'number', min: 0.1, message: '每分钟消耗卡路里必须大于0.1', trigger: 'blur' }
  ]
}

// 分类选项
const categoryOptions = [
  { value: 'CARDIO', label: '有氧运动' },
  { value: 'STRENGTH', label: '力量训练' },
  { value: 'FLEXIBILITY', label: '柔韧性训练' },
  { value: 'BALANCE', label: '平衡训练' },
  { value: 'SPORTS', label: '体育运动' },
  { value: 'OTHER', label: '其他' }
]

// 获取分类显示名称
const getCategoryDisplayName = (category) => {
  const option = categoryOptions.find(opt => opt.value === category)
  return option ? option.label : category
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  currentId.value = null
  form.value = {
    name: '',
    category: '',
    caloriesPerMinute: 5.0,
    description: ''
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEdit.value = true
  currentId.value = row.id
  form.value = {
    name: row.name,
    category: row.category,
    caloriesPerMinute: row.caloriesPerMinute,
    description: row.description || ''
  }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该运动类型吗？若存在关联的运动记录，它们也将被一并删除。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteExerciseType(row.id)
      ElMessage.success(response.message || '删除成功')
      fetchExerciseTypes()
    } catch (error) {
      console.error('删除运动类型失败:', error)
      ElMessage.error(error.response?.data?.message || '删除运动类型失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    
    try {
      const submitData = {
        name: form.value.name,
        category: form.value.category,
        caloriesPerMinute: form.value.caloriesPerMinute,
        description: form.value.description
      }
      
      if (isEdit.value) {
        await updateExerciseType(currentId.value, submitData)
        ElMessage.success('更新成功')
      } else {
        await createExerciseType(submitData)
        ElMessage.success('添加成功')
      }
      
      dialogVisible.value = false
      fetchExerciseTypes()
    } catch (error) {
      console.error('保存运动类型失败:', error)
      ElMessage.error(error.response?.data?.message || '保存运动类型失败')
    } finally {
      submitting.value = false
    }
  })
}

// 获取所有运动类型
const fetchExerciseTypes = async () => {
  loading.value = true
  
  try {
    exerciseTypes.value = await getAllExerciseTypes()
  } catch (error) {
    console.error('获取运动类型失败:', error)
    ElMessage.error('获取运动类型失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchExerciseTypes()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.action-card {
  margin-bottom: 20px;
}

.action-container {
  display: flex;
  justify-content: flex-end;
}

.table-card {
  margin-bottom: 20px;
}
</style> 